package adapter

import (
	"context"
	"fmt"
	"sync"
	"time"

	"gitee.com/rw555/fdsmastergo/pkg/audioplayer"
	"gitee.com/rw555/fdsmastergo/pkg/logger"
	"go.uber.org/zap"
)

// VirtualPlayer 是一个虚拟的音频播放器，不实际播放音频但实现了AudioPlayer接口
type VirtualPlayer struct {
	mutex            sync.Mutex
	status           audioplayer.PlaybackStatus
	position         float64
	duration         float64
	volume           float64
	source           *audioplayer.AudioSource
	playlist         []*audioplayer.AudioSource
	playlistMutex    sync.RWMutex
	supportedFormats []audioplayer.AudioFormat
	eventHandlers    map[audioplayer.PlaybackEventType][]audioplayer.PlaybackEventHandler
	stopPlayback     chan struct{}
	stopUpdateLoop   chan struct{}
}

// NewVirtualPlayer 创建一个新的虚拟播放器
func NewVirtualPlayer() (*VirtualPlayer, error) {
	return &VirtualPlayer{
		status:           audioplayer.StatusStopped,
		position:         0,
		duration:         0,
		volume:           0.8,
		supportedFormats: []audioplayer.AudioFormat{audioplayer.FormatMP3, audioplayer.FormatWAV, audioplayer.FormatOGG, audioplayer.FormatFLAC},
		eventHandlers:    make(map[audioplayer.PlaybackEventType][]audioplayer.PlaybackEventHandler),
		stopPlayback:     make(chan struct{}),
		stopUpdateLoop:   make(chan struct{}),
		playlist:         make([]*audioplayer.AudioSource, 0),
	}, nil
}

// Play 模拟播放音频
func (v *VirtualPlayer) Play(ctx context.Context, source audioplayer.AudioSource) error {
	v.mutex.Lock()
	defer v.mutex.Unlock()

	// 停止当前播放
	select {
	case v.stopPlayback <- struct{}{}:
		// 已成功发送停止信号
	default:
		// 通道已关闭或没有接收者，这是正常的
	}

	// 复制源，确保不会被外部修改
	sourceCopy := source
	v.source = &sourceCopy
	v.position = 0
	v.duration = 180.0 // 假设所有文件都是3分钟长

	// 设置状态为播放
	v.status = audioplayer.StatusPlaying

	// 触发开始播放事件
	v.triggerEvent(audioplayer.EventPlaybackStarted)

	// 启动一个goroutine来模拟播放进度
	stopChan := make(chan struct{})
	v.stopPlayback = stopChan

	go func() {
		ticker := time.NewTicker(1 * time.Second)
		defer ticker.Stop()

		for {
			select {
			case <-ticker.C:
				v.mutex.Lock()
				if v.status == audioplayer.StatusPlaying {
					v.position += 1.0
					if v.position >= v.duration {
						v.position = 0
						v.status = audioplayer.StatusStopped
						v.triggerEvent(audioplayer.EventPlaybackCompleted)
						v.mutex.Unlock()
						return
					}
					v.triggerEvent(audioplayer.EventPositionChanged)
				}
				v.mutex.Unlock()
			case <-stopChan:
				return
			case <-ctx.Done():
				return
			}
		}
	}()

	logger.SystemInfo("虚拟播放开始", zap.String("file", source.Path))
	return nil
}

// Pause 暂停播放
func (v *VirtualPlayer) Pause(ctx context.Context) error {
	v.mutex.Lock()
	defer v.mutex.Unlock()

	if v.status != audioplayer.StatusPlaying {
		return fmt.Errorf("没有正在播放的音频可暂停")
	}

	v.status = audioplayer.StatusPaused
	v.triggerEvent(audioplayer.EventPlaybackPaused)
	logger.SystemInfo("虚拟播放暂停")
	return nil
}

// Resume 恢复播放
func (v *VirtualPlayer) Resume(ctx context.Context) error {
	v.mutex.Lock()
	defer v.mutex.Unlock()

	if v.status != audioplayer.StatusPaused {
		return fmt.Errorf("没有暂停的音频可恢复")
	}

	v.status = audioplayer.StatusPlaying
	v.triggerEvent(audioplayer.EventPlaybackResumed)
	logger.SystemInfo("虚拟播放恢复")
	return nil
}

// Stop 停止播放
func (v *VirtualPlayer) Stop(ctx context.Context) error {
	v.mutex.Lock()
	defer v.mutex.Unlock()

	if v.status == audioplayer.StatusStopped {
		return nil
	}

	// 停止播放进度更新
	select {
	case v.stopPlayback <- struct{}{}:
		// 成功发送停止信号
	default:
		// 通道已关闭或没有接收者
	}

	v.status = audioplayer.StatusStopped
	v.position = 0
	v.triggerEvent(audioplayer.EventPlaybackStopped)
	logger.SystemInfo("虚拟播放停止")
	return nil
}

// IsPlaying 返回是否正在播放
func (v *VirtualPlayer) IsPlaying() bool {
	v.mutex.Lock()
	defer v.mutex.Unlock()
	return v.status == audioplayer.StatusPlaying
}

// Seek 跳转到指定位置
func (v *VirtualPlayer) Seek(ctx context.Context, position float64) error {
	v.mutex.Lock()
	defer v.mutex.Unlock()

	if v.status == audioplayer.StatusStopped {
		return fmt.Errorf("没有正在播放的音频")
	}

	if position < 0 {
		position = 0
	}
	if position > v.duration {
		position = v.duration
	}

	v.position = position
	v.triggerEvent(audioplayer.EventPositionChanged)
	logger.SystemInfo("虚拟播放跳转", zap.Float64("position", position))
	return nil
}

// GetPosition 获取当前播放位置
func (v *VirtualPlayer) GetPosition() float64 {
	v.mutex.Lock()
	defer v.mutex.Unlock()
	return v.position
}

// GetDuration 获取音频总时长
func (v *VirtualPlayer) GetDuration() float64 {
	v.mutex.Lock()
	defer v.mutex.Unlock()
	return v.duration
}

// SetVolume 设置音量
func (v *VirtualPlayer) SetVolume(volume float64) error {
	v.mutex.Lock()
	defer v.mutex.Unlock()

	if volume < 0 {
		volume = 0
	}
	if volume > 1.0 {
		volume = 1.0
	}

	v.volume = volume
	logger.SystemInfo("虚拟播放器设置音量", zap.Float64("volume", volume))
	return nil
}

// GetVolume 获取音量
func (v *VirtualPlayer) GetVolume() float64 {
	v.mutex.Lock()
	defer v.mutex.Unlock()
	return v.volume
}

// GetPlaybackInfo 获取播放信息
func (v *VirtualPlayer) GetPlaybackInfo() audioplayer.PlaybackInfo {
	v.mutex.Lock()
	defer v.mutex.Unlock()

	info := audioplayer.PlaybackInfo{
		Status:    v.status,
		Position:  v.position,
		Duration:  v.duration,
		Volume:    v.volume,
		Source:    v.source,
		IsLooping: false,
	}

	return info
}

// AddToPlaylist 添加到播放列表
func (v *VirtualPlayer) AddToPlaylist(source audioplayer.AudioSource) error {
	v.playlistMutex.Lock()
	defer v.playlistMutex.Unlock()

	sourceCopy := source
	v.playlist = append(v.playlist, &sourceCopy)
	return nil
}

// RemoveFromPlaylist 从播放列表移除
func (v *VirtualPlayer) RemoveFromPlaylist(index int) error {
	v.playlistMutex.Lock()
	defer v.playlistMutex.Unlock()

	if index < 0 || index >= len(v.playlist) {
		return fmt.Errorf("播放列表索引越界: %d", index)
	}

	v.playlist = append(v.playlist[:index], v.playlist[index+1:]...)
	return nil
}

// ClearPlaylist 清空播放列表
func (v *VirtualPlayer) ClearPlaylist() error {
	v.playlistMutex.Lock()
	defer v.playlistMutex.Unlock()

	v.playlist = make([]*audioplayer.AudioSource, 0)
	return nil
}

// GetPlaylist 获取播放列表
func (v *VirtualPlayer) GetPlaylist() ([]audioplayer.AudioSource, error) {
	v.playlistMutex.RLock()
	defer v.playlistMutex.RUnlock()

	result := make([]audioplayer.AudioSource, len(v.playlist))
	for i, src := range v.playlist {
		result[i] = *src // 复制对象
	}

	return result, nil
}

// PlayNext 播放下一首
func (v *VirtualPlayer) PlayNext(ctx context.Context) error {
	v.playlistMutex.Lock()

	if len(v.playlist) == 0 {
		v.playlistMutex.Unlock()
		return fmt.Errorf("播放列表为空")
	}

	currentPath := ""
	v.mutex.Lock()
	if v.source != nil {
		currentPath = v.source.Path
	}
	v.mutex.Unlock()

	currentIndex := -1
	for i, src := range v.playlist {
		if src.Path == currentPath {
			currentIndex = i
			break
		}
	}

	var nextSource *audioplayer.AudioSource
	if currentIndex == -1 || currentIndex >= len(v.playlist)-1 {
		nextSource = v.playlist[0]
	} else {
		nextSource = v.playlist[currentIndex+1]
	}

	v.playlistMutex.Unlock()

	return v.Play(ctx, *nextSource)
}

// PlayPrevious 播放上一首
func (v *VirtualPlayer) PlayPrevious(ctx context.Context) error {
	v.playlistMutex.Lock()

	if len(v.playlist) == 0 {
		v.playlistMutex.Unlock()
		return fmt.Errorf("播放列表为空")
	}

	currentPath := ""
	v.mutex.Lock()
	if v.source != nil {
		currentPath = v.source.Path
	}
	v.mutex.Unlock()

	currentIndex := -1
	for i, src := range v.playlist {
		if src.Path == currentPath {
			currentIndex = i
			break
		}
	}

	var prevSource *audioplayer.AudioSource
	if currentIndex <= 0 {
		prevSource = v.playlist[len(v.playlist)-1]
	} else {
		prevSource = v.playlist[currentIndex-1]
	}

	v.playlistMutex.Unlock()

	return v.Play(ctx, *prevSource)
}

// GetSupportedFormats 获取支持的格式
func (v *VirtualPlayer) GetSupportedFormats() []audioplayer.AudioFormat {
	return v.supportedFormats
}

// RegisterEventHandler 注册事件处理器
func (v *VirtualPlayer) RegisterEventHandler(eventType audioplayer.PlaybackEventType, handler audioplayer.PlaybackEventHandler) {
	v.mutex.Lock()
	defer v.mutex.Unlock()

	if v.eventHandlers == nil {
		v.eventHandlers = make(map[audioplayer.PlaybackEventType][]audioplayer.PlaybackEventHandler)
	}

	v.eventHandlers[eventType] = append(v.eventHandlers[eventType], handler)
}

// UnregisterEventHandler 注销事件处理器
func (v *VirtualPlayer) UnregisterEventHandler(eventType audioplayer.PlaybackEventType, handler audioplayer.PlaybackEventHandler) {
	v.mutex.Lock()
	defer v.mutex.Unlock()

	if v.eventHandlers == nil {
		return
	}

	handlers, exists := v.eventHandlers[eventType]
	if !exists {
		return
	}

	for i, h := range handlers {
		if fmt.Sprintf("%p", h) == fmt.Sprintf("%p", handler) {
			v.eventHandlers[eventType] = append(handlers[:i], handlers[i+1:]...)
			break
		}
	}
}

// Initialize 初始化播放器
func (v *VirtualPlayer) Initialize() error {
	return nil
}

// Close 关闭播放器
func (v *VirtualPlayer) Close() error {
	// 停止所有后台goroutine
	select {
	case v.stopPlayback <- struct{}{}:
		// 成功发送停止信号
	default:
		// 通道已关闭或没有接收者
	}

	select {
	case v.stopUpdateLoop <- struct{}{}:
		// 成功发送停止信号
	default:
		// 通道已关闭或没有接收者
	}

	return nil
}

// triggerEvent 触发事件
func (v *VirtualPlayer) triggerEvent(eventType audioplayer.PlaybackEventType) {
	if v.eventHandlers == nil {
		return
	}

	handlers, exists := v.eventHandlers[eventType]
	if !exists || len(handlers) == 0 {
		return
	}

	event := audioplayer.PlaybackEvent{
		Type:      eventType,
		Timestamp: time.Now(),
		Info:      v.GetPlaybackInfo(),
	}

	for _, handler := range handlers {
		go func(h audioplayer.PlaybackEventHandler) {
			defer func() {
				if r := recover(); r != nil {
					logger.SystemError("事件处理器异常", zap.Any("panic", r))
				}
			}()
			h(event)
		}(handler)
	}
}
